import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sms_listener/sms_listener.dart';
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SMS监听和发送完整测试',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: SmsTestHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class SmsTestHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: Text('SMS监听和发送测试'),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          bottom: TabBar(
            tabs: [
              Tab(icon: Icon(Icons.hearing), text: '短信监听'),
              Tab(icon: Icon(Icons.send), text: '短信发送'),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            SmsListenerTestPage(),
            SmsSenderTestPage(),
          ],
        ),
      ),
    );
  }
}

class SmsSenderTestPage extends StatefulWidget {
  @override
  _SmsSenderTestPageState createState() => _SmsSenderTestPageState();
}

class _SmsSenderTestPageState extends State<SmsSenderTestPage> {
  final SmsListener _smsListener = SmsListener();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _messageController = TextEditingController();

  bool _hasSendPermission = false;
  bool _isSmsAvailable = false;
  String _defaultSmsApp = '';
  String _statusMessage = '准备就绪';
  List<SmsSendResult> _sendResults = [];
  bool _isSending = false;

  @override
  void initState() {
    super.initState();
    _initializeSender();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _messageController.dispose();
    super.dispose();
  }

  /// 初始化发送器
  Future<void> _initializeSender() async {
    await _checkSendPermission();
    await _checkSmsAvailability();
    await _getDefaultSmsApp();
  }

  /// 检查发送权限
  Future<void> _checkSendPermission() async {
    try {
      final hasPermission = await _smsListener.hasSendPermission();
      setState(() {
        _hasSendPermission = hasPermission;
        _statusMessage = hasPermission ? '已有发送权限' : '需要申请发送权限';
      });
    } catch (e) {
      _updateStatus('检查发送权限失败: $e');
    }
  }

  /// 检查短信功能可用性
  Future<void> _checkSmsAvailability() async {
    try {
      final isAvailable = await _smsListener.isSmsAvailable();
      setState(() {
        _isSmsAvailable = isAvailable;
      });
    } catch (e) {
      print('检查短信功能可用性失败: $e');
    }
  }

  /// 获取默认短信应用
  Future<void> _getDefaultSmsApp() async {
    try {
      final defaultApp = await _smsListener.getDefaultSmsApp();
      setState(() {
        _defaultSmsApp = defaultApp ?? '未知';
      });
    } catch (e) {
      print('获取默认短信应用失败: $e');
    }
  }

  /// 请求发送权限
  Future<void> _requestSendPermission() async {
    try {
      _updateStatus('正在请求发送权限...');
      final granted = await _smsListener.requestSendPermission();
      setState(() {
        _hasSendPermission = granted;
        _statusMessage = granted ? '发送权限获取成功' : '发送权限被拒绝';
      });

      if (!granted) {
        _showPermissionDialog();
      }
    } catch (e) {
      _updateStatus('请求发送权限失败: $e');
    }
  }

  /// 显示权限说明对话框
  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Row(
            children: [
              Icon(Icons.security, color: Colors.orange),
              SizedBox(width: 8),
              Text('需要发送权限'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('此应用需要SMS发送权限来测试短信发送功能。'),
              SizedBox(height: 16),
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.blue[200]!),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('权限用途：',
                        style: TextStyle(fontWeight: FontWeight.bold)),
                    Text('• 发送短信权限：直接后台发送短信'),
                    Text('• 注意：会产生短信费用'),
                  ],
                ),
              ),
              SizedBox(height: 16),
              Text('请在设置中手动开启发送权限。',
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.red)),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('取消'),
            ),
            ElevatedButton.icon(
              onPressed: () async {
                Navigator.of(context).pop();
                await SmsPermissions.openAppSettings();
              },
              icon: Icon(Icons.settings),
              label: Text('去设置'),
            ),
          ],
        );
      },
    );
  }

  /// 后台发送短信
  Future<void> _sendSmsBackground() async {
    if (!_validateInput()) return;

    setState(() {
      _isSending = true;
    });

    try {
      _updateStatus('正在后台发送短信...');
      final result = await _smsListener.sendSmsBackground(
        phoneNumber: _phoneController.text.trim(),
        message: _messageController.text,
        requestPermissionIfNeeded: true,
      );

      _addSendResult(result);

      if (result.isSuccess) {
        _updateStatus('短信发送成功');
        _showSuccessDialog('后台发送成功', '短信已通过后台方式发送');
      } else {
        _updateStatus('短信发送失败: ${result.errorMessage}');
        _showErrorDialog('后台发送失败', result.errorMessage ?? '未知错误');
      }
    } catch (e) {
      _updateStatus('发送短信时发生错误: $e');
      _showErrorDialog('发送错误', e.toString());
    } finally {
      setState(() {
        _isSending = false;
      });
    }
  }

  /// 系统界面发送短信
  Future<void> _sendSmsWithIntent() async {
    if (!_validateInput()) return;

    setState(() {
      _isSending = true;
    });

    try {
      _updateStatus('正在打开系统短信界面...');
      final result = await _smsListener.sendSmsWithSystemIntent(
        phoneNumber: _phoneController.text.trim(),
        message: _messageController.text,
      );

      _addSendResult(result);

      if (result.isSuccess) {
        _updateStatus('系统短信界面已打开');
        _showInfoDialog('系统界面已打开', '请在系统短信应用中完成发送');
      } else {
        _updateStatus('打开系统短信界面失败: ${result.errorMessage}');
        _showErrorDialog('系统界面打开失败', result.errorMessage ?? '未知错误');
      }
    } catch (e) {
      _updateStatus('打开系统短信界面时发生错误: $e');
      _showErrorDialog('操作错误', e.toString());
    } finally {
      setState(() {
        _isSending = false;
      });
    }
  }

  /// 智能发送短信
  Future<void> _sendSmsSmart() async {
    if (!_validateInput()) return;

    setState(() {
      _isSending = true;
    });

    try {
      _updateStatus('正在智能发送短信...');
      final result = await _smsListener.sendSms(
        phoneNumber: _phoneController.text.trim(),
        message: _messageController.text,
        requestPermissionIfNeeded: true,
        fallbackToIntent: true,
      );

      _addSendResult(result);

      if (result.isSuccess) {
        String modeText =
            result.mode == SmsSendMode.background ? '后台模式' : '系统界面模式';
        _updateStatus('短信发送成功 ($modeText)');
        _showSuccessDialog('智能发送成功', '短信已通过$modeText发送');
      } else {
        _updateStatus('短信发送失败: ${result.errorMessage}');
        _showErrorDialog('智能发送失败', result.errorMessage ?? '未知错误');
      }
    } catch (e) {
      _updateStatus('发送短信时发生错误: $e');
      _showErrorDialog('发送错误', e.toString());
    } finally {
      setState(() {
        _isSending = false;
      });
    }
  }

  /// 验证输入
  bool _validateInput() {
    final phone = _phoneController.text.trim();
    final message = _messageController.text.trim();

    if (phone.isEmpty) {
      _showErrorDialog('输入错误', '请输入手机号码');
      return false;
    }

    if (message.isEmpty) {
      _showErrorDialog('输入错误', '请输入短信内容');
      return false;
    }

    return true;
  }

  /// 添加发送结果
  void _addSendResult(SmsSendResult result) {
    setState(() {
      _sendResults.insert(0, result);
      if (_sendResults.length > 50) {
        _sendResults.removeRange(50, _sendResults.length);
      }
    });
  }

  /// 更新状态消息
  void _updateStatus(String message) {
    setState(() {
      _statusMessage = message;
    });
  }

  /// 显示成功对话框
  void _showSuccessDialog(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.check_circle, color: Colors.green),
            SizedBox(width: 8),
            Text(title),
          ],
        ),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示错误对话框
  void _showErrorDialog(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.error, color: Colors.red),
            SizedBox(width: 8),
            Text(title),
          ],
        ),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示信息对话框
  void _showInfoDialog(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.info, color: Colors.blue),
            SizedBox(width: 8),
            Text(title),
          ],
        ),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 清空发送结果
  void _clearResults() {
    setState(() {
      _sendResults.clear();
    });
  }

  /// 显示系统信息
  void _showSystemInfo() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.info_outline),
            SizedBox(width: 8),
            Text('系统信息'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoRow('发送权限', _hasSendPermission ? '已授予' : '未授予'),
            _buildInfoRow('短信功能', _isSmsAvailable ? '可用' : '不可用'),
            _buildInfoRow('默认短信应用', _defaultSmsApp),
            SizedBox(height: 16),
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue[50],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('发送模式说明：',
                      style: TextStyle(fontWeight: FontWeight.bold)),
                  Text('• 后台发送：需要SEND_SMS权限，直接发送'),
                  Text('• 系统界面：无需权限，打开系统短信应用'),
                  Text('• 智能发送：优先后台，失败时回退到系统界面'),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Text(label + ':', style: TextStyle(fontWeight: FontWeight.w500)),
          Spacer(),
          Text(value),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 状态卡片
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.send,
                          color:
                              _hasSendPermission ? Colors.green : Colors.grey,
                        ),
                        SizedBox(width: 8),
                        Text(
                          '发送状态',
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                        Spacer(),
                        IconButton(
                          onPressed: _showSystemInfo,
                          icon: Icon(Icons.info_outline),
                          tooltip: '系统信息',
                        ),
                      ],
                    ),
                    SizedBox(height: 8),
                    Text(_statusMessage),
                    SizedBox(height: 8),
                    Row(
                      children: [
                        Icon(
                          _hasSendPermission ? Icons.check_circle : Icons.error,
                          color: _hasSendPermission ? Colors.green : Colors.red,
                          size: 16,
                        ),
                        SizedBox(width: 4),
                        Text(
                          _hasSendPermission ? '已有发送权限' : '缺少发送权限',
                          style: TextStyle(
                            color:
                                _hasSendPermission ? Colors.green : Colors.red,
                          ),
                        ),
                        SizedBox(width: 16),
                        Icon(
                          _isSmsAvailable
                              ? Icons.phone_android
                              : Icons.phone_disabled,
                          color: _isSmsAvailable ? Colors.green : Colors.grey,
                          size: 16,
                        ),
                        SizedBox(width: 4),
                        Text(
                          _isSmsAvailable ? '短信功能可用' : '短信功能不可用',
                          style: TextStyle(
                            color: _isSmsAvailable ? Colors.green : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 输入区域
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '短信内容',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    SizedBox(height: 12),
                    TextField(
                      controller: _phoneController,
                      decoration: InputDecoration(
                        labelText: '手机号码',
                        hintText: '请输入接收者手机号码',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.phone),
                      ),
                      keyboardType: TextInputType.phone,
                    ),
                    SizedBox(height: 12),
                    TextField(
                      controller: _messageController,
                      decoration: InputDecoration(
                        labelText: '短信内容',
                        hintText: '请输入要发送的短信内容',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.message),
                      ),
                      maxLines: 3,
                      maxLength: 500,
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 权限按钮
            if (!_hasSendPermission)
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: _requestSendPermission,
                  icon: Icon(Icons.security),
                  label: Text('申请发送权限'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    foregroundColor: Colors.white,
                  ),
                ),
              ),

            if (!_hasSendPermission) SizedBox(height: 16),

            // 发送按钮
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _isSending ? null : _sendSmsBackground,
                    icon: _isSending
                        ? SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : Icon(Icons.send),
                    label: Text('后台发送'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _isSending ? null : _sendSmsWithIntent,
                    icon: Icon(Icons.open_in_new),
                    label: Text('系统界面'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),

            SizedBox(height: 8),

            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: _isSending ? null : _sendSmsSmart,
                icon: Icon(Icons.auto_awesome),
                label: Text('智能发送 (推荐)'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.purple,
                  foregroundColor: Colors.white,
                ),
              ),
            ),

            SizedBox(height: 16),

            // 发送结果标题
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '发送结果 (${_sendResults.length})',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                if (_sendResults.isNotEmpty)
                  IconButton(
                    onPressed: _clearResults,
                    icon: Icon(Icons.clear),
                    tooltip: '清空结果',
                  ),
              ],
            ),

            SizedBox(height: 8),

            // 发送结果列表
            Expanded(
              child: _sendResults.isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.send_outlined,
                              size: 64, color: Colors.grey),
                          SizedBox(height: 16),
                          Text(
                            '暂无发送记录',
                            style: TextStyle(color: Colors.grey, fontSize: 18),
                          ),
                          SizedBox(height: 8),
                          Text(
                            '发送短信后，结果会显示在这里',
                            style: TextStyle(color: Colors.grey, fontSize: 12),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    )
                  : ListView.builder(
                      itemCount: _sendResults.length,
                      itemBuilder: (context, index) {
                        final result = _sendResults[index];
                        return Card(
                          margin: EdgeInsets.only(bottom: 8),
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundColor:
                                  result.isSuccess ? Colors.green : Colors.red,
                              child: Icon(
                                result.isSuccess ? Icons.check : Icons.error,
                                color: Colors.white,
                                size: 20,
                              ),
                            ),
                            title: Row(
                              children: [
                                Text(
                                  result.isSuccess ? '发送成功' : '发送失败',
                                  style: TextStyle(fontWeight: FontWeight.bold),
                                ),
                                Spacer(),
                                Container(
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 6, vertical: 2),
                                  decoration: BoxDecoration(
                                    color: result.mode == SmsSendMode.background
                                        ? Colors.blue[100]
                                        : Colors.green[100],
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Text(
                                    result.mode == SmsSendMode.background
                                        ? '后台'
                                        : '系统',
                                    style: TextStyle(
                                      fontSize: 10,
                                      color:
                                          result.mode == SmsSendMode.background
                                              ? Colors.blue[700]
                                              : Colors.green[700],
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            subtitle: Text(
                              result.isSuccess
                                  ? '发送方式: ${result.mode == SmsSendMode.background ? "后台直接发送" : "系统界面发送"}'
                                  : '错误信息: ${result.errorMessage}',
                            ),
                            trailing: Icon(Icons.arrow_forward_ios, size: 16),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

class SmsListenerTestPage extends StatefulWidget {
  @override
  _SmsListenerTestPageState createState() => _SmsListenerTestPageState();
}

class _SmsListenerTestPageState extends State<SmsListenerTestPage>
    with WidgetsBindingObserver {
  final SmsListener _smsListener = SmsListener();
  List<SmsMessage> _receivedMessages = [];
  List<SmsMessage> _historyMessages = [];
  bool _isListening = false;
  bool _hasPermissions = false;
  String _statusMessage = '准备就绪';
  String _errorMessage = '';
  int _messageCount = 0;
  int _totalReceived = 0;
  bool _enableBackground = true;
  List<String> _filterSenders = [];
  final TextEditingController _filterController = TextEditingController();

  // 新增状态变量
  bool _foregroundServiceRunning = false;
  DateTime? _lastSmsTime;
  String _appLifecycleState = 'resumed';
  bool _autoStartListening = true;
  bool _showDebugInfo = false;
  List<String> _debugLogs = [];
  Map<String, int> _senderStats = {};

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initializeApp();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _smsListener.dispose();
    _filterController.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _appLifecycleState = state.name;
    });
    _addDebugLog('应用状态变化: ${state.name}');

    if (state == AppLifecycleState.resumed && _autoStartListening) {
      // 应用回到前台时检查监听状态
      _checkListeningStatus();
    }
  }

  /// 初始化应用
  Future<void> _initializeApp() async {
    _addDebugLog('开始初始化应用');
    await _checkPermissions();
    await _loadSmsHistory();

    if (_hasPermissions && _autoStartListening) {
      await _startListening();
    }
  }

  /// 添加调试日志
  void _addDebugLog(String log) {
    if (_debugLogs.length > 100) {
      _debugLogs.removeAt(0);
    }
    _debugLogs.add('${DateTime.now().toString().substring(11, 19)} - $log');
    print('SMS监听器: $log');
  }

  /// 检查监听状态
  Future<void> _checkListeningStatus() async {
    final isListening = _smsListener.isListening;
    if (isListening != _isListening) {
      setState(() {
        _isListening = isListening;
      });
      _addDebugLog('监听状态同步: $_isListening');
    }
  }

  /// 检查权限状态
  Future<void> _checkPermissions() async {
    try {
      final hasPermissions = await _smsListener.hasPermissions();
      setState(() {
        _hasPermissions = hasPermissions;
        _statusMessage = hasPermissions ? '已有权限' : '需要申请权限';
        _errorMessage = '';
      });
      _addDebugLog('权限检查结果: $hasPermissions');
    } catch (e) {
      _updateError('检查权限失败: $e');
    }
  }

  /// 请求权限
  Future<void> _requestPermissions() async {
    try {
      _updateStatus('正在请求权限...');
      _addDebugLog('开始请求权限');

      final granted = await _smsListener.requestPermissions();

      setState(() {
        _hasPermissions = granted;
        _statusMessage = granted ? '权限获取成功' : '权限被拒绝';
        _errorMessage = '';
      });

      _addDebugLog('权限请求结果: $granted');

      if (!granted) {
        _showPermissionDialog();
      } else if (_autoStartListening) {
        await _startListening();
      }
    } catch (e) {
      _updateError('请求权限失败: $e');
    }
  }

  /// 显示权限说明对话框
  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Row(
            children: [
              Icon(Icons.security, color: Colors.orange),
              SizedBox(width: 8),
              Text('需要短信权限'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('此应用需要短信权限来测试监听功能。'),
              SizedBox(height: 16),
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.blue[200]!),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('权限用途：',
                        style: TextStyle(fontWeight: FontWeight.bold)),
                    Text('• 接收短信权限：监听新短信'),
                    Text('• 读取短信权限：获取短信内容'),
                    Text('• 前台服务权限：后台持续监听'),
                  ],
                ),
              ),
              SizedBox(height: 16),
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.orange[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.orange[200]!),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('注意事项：',
                        style: TextStyle(fontWeight: FontWeight.bold)),
                    Text('• 后台监听会显示持续通知'),
                    Text('• 某些设备需关闭电池优化'),
                    Text('• 请确保允许后台活动'),
                  ],
                ),
              ),
              SizedBox(height: 16),
              Text('请在设置中手动开启权限。',
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.red)),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('取消'),
            ),
            ElevatedButton.icon(
              onPressed: () async {
                Navigator.of(context).pop();
                await SmsPermissions.openAppSettings();
              },
              icon: Icon(Icons.settings),
              label: Text('去设置'),
            ),
          ],
        );
      },
    );
  }

  /// 开始监听短信
  Future<void> _startListening() async {
    if (!_hasPermissions) {
      await _requestPermissions();
      return;
    }

    try {
      _updateStatus('正在启动监听...');
      _addDebugLog('开始启动SMS监听');

      // 配置监听器
      await _smsListener.configure(
        enableBackground: _enableBackground,
        filterSenders: _filterSenders.isNotEmpty ? _filterSenders : null,
      );
      _addDebugLog('监听器配置完成 - 后台:$_enableBackground, 过滤器:$_filterSenders');

      await _smsListener.startListening(
        (SmsMessage message) {
          _addDebugLog('收到新短信: ${message.address} - ${message.body}');
          setState(() {
            _receivedMessages.insert(0, message);
            _messageCount++;
            _totalReceived++;
            _lastSmsTime = message.date;
            _statusMessage = '监听中 - 已收到 $_messageCount 条短信';

            // 更新发送者统计
            _senderStats[message.address] =
                (_senderStats[message.address] ?? 0) + 1;
          });

          // 显示通知
          _showSmsNotification(message);
        },
        onError: (String error) {
          _addDebugLog('监听错误: $error');
          _updateError('监听错误: $error');
        },
        enableBackground: _enableBackground,
        filterSenders: _filterSenders.isNotEmpty ? _filterSenders : null,
      );

      setState(() {
        _isListening = _smsListener.isListening;
        _foregroundServiceRunning = _enableBackground;
        if (_isListening) {
          _statusMessage = '监听中 - 等待新短信';
          _errorMessage = '';
        }
      });

      _addDebugLog('SMS监听启动成功');
    } catch (e) {
      _addDebugLog('启动监听失败: $e');
      _updateError('启动监听失败: $e');
    }
  }

  /// 停止监听短信
  Future<void> _stopListening() async {
    try {
      _addDebugLog('开始停止SMS监听');
      await _smsListener.stopListening();
      setState(() {
        _isListening = false;
        _foregroundServiceRunning = false;
        _statusMessage = '已停止监听';
        _errorMessage = '';
      });
      _addDebugLog('SMS监听已停止');
    } catch (e) {
      _addDebugLog('停止监听失败: $e');
      _updateError('停止监听失败: $e');
    }
  }

  /// 加载短信历史
  Future<void> _loadSmsHistory() async {
    if (!_hasPermissions) {
      return;
    }

    try {
      _updateStatus('正在加载短信历史...');
      _addDebugLog('开始加载短信历史');

      final history = await _smsListener.getSmsHistory(limit: 50);
      setState(() {
        _historyMessages = history;
        _statusMessage = '已加载 ${history.length} 条历史短信';
        _errorMessage = '';
      });
      _addDebugLog('短信历史加载完成: ${history.length}条');
    } catch (e) {
      _addDebugLog('加载历史短信失败: $e');
      _updateError('加载历史短信失败: $e');
    }
  }

  /// 获取最后一条短信
  Future<void> _getLastSms() async {
    if (!_hasPermissions) {
      await _requestPermissions();
      return;
    }

    try {
      _updateStatus('正在获取最后一条短信...');
      _addDebugLog('获取最后一条短信');

      final lastSms = await _smsListener.getLastSms();
      if (lastSms != null) {
        _showSmsDetails(lastSms, title: '最后一条短信');
        _updateStatus('获取成功');
        _addDebugLog('获取最后一条短信成功');
      } else {
        _updateStatus('没有找到短信');
        _addDebugLog('没有找到短信');
      }
    } catch (e) {
      _addDebugLog('获取最后一条短信失败: $e');
      _updateError('获取最后一条短信失败: $e');
    }
  }

  /// 显示短信通知
  void _showSmsNotification(SmsMessage message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Icon(Icons.message, color: Colors.white, size: 20),
                SizedBox(width: 8),
                Text('收到新短信', style: TextStyle(fontWeight: FontWeight.bold)),
                Spacer(),
                Text(DateTime.now().toString().substring(11, 19),
                    style: TextStyle(fontSize: 12)),
              ],
            ),
            SizedBox(height: 4),
            Text('发送者: ${message.address}'),
            Text(
                '内容: ${message.body.length > 30 ? message.body.substring(0, 30) + '...' : message.body}'),
          ],
        ),
        duration: Duration(seconds: 5),
        backgroundColor: Colors.green,
        action: SnackBarAction(
          label: '查看',
          textColor: Colors.white,
          onPressed: () => _showSmsDetails(message),
        ),
      ),
    );
  }

  /// 显示短信详情
  void _showSmsDetails(SmsMessage message, {String title = '短信详情'}) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Row(
            children: [
              Icon(Icons.message_outlined),
              SizedBox(width: 8),
              Expanded(child: Text(title)),
            ],
          ),
          content: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildDetailRow('发送者', message.address),
                SizedBox(height: 12),
                _buildDetailRow('时间', message.formattedDate),
                SizedBox(height: 12),
                _buildDetailRow('类型', message.isReceived ? '接收' : '发送'),
                SizedBox(height: 12),
                _buildDetailRow(
                    '时间戳', message.date.millisecondsSinceEpoch.toString()),
                SizedBox(height: 12),
                _buildDetailRow('内容', message.body),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Clipboard.setData(ClipboardData(text: message.body));
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('短信内容已复制')),
                );
              },
              child: Text('复制'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('关闭'),
            ),
          ],
        );
      },
    );
  }

  /// 构建详情行
  Widget _buildDetailRow(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.grey[600],
            fontSize: 12,
          ),
        ),
        SizedBox(height: 4),
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            value,
            style: TextStyle(fontSize: 14),
          ),
        ),
      ],
    );
  }

  /// 更新状态消息
  void _updateStatus(String message) {
    setState(() {
      _statusMessage = message;
      _errorMessage = '';
    });
  }

  /// 更新错误消息
  void _updateError(String error) {
    setState(() {
      _errorMessage = error;
    });
    _addDebugLog('错误: $error');
  }

  /// 清空消息列表
  void _clearMessages() {
    setState(() {
      _receivedMessages.clear();
      _messageCount = 0;
      _statusMessage = _isListening ? '监听中 - 等待新短信' : '已停止监听';
    });
    _addDebugLog('已清空消息列表');
  }

  /// 重置统计
  void _resetStats() {
    setState(() {
      _totalReceived = 0;
      _senderStats.clear();
      _lastSmsTime = null;
    });
    _addDebugLog('统计数据已重置');
  }

  /// 添加发送者过滤
  void _addSenderFilter() {
    final sender = _filterController.text.trim();
    if (sender.isNotEmpty && !_filterSenders.contains(sender)) {
      setState(() {
        _filterSenders.add(sender);
        _filterController.clear();
      });
      _addDebugLog('添加发送者过滤: $sender');
    }
  }

  /// 移除发送者过滤
  void _removeSenderFilter(String sender) {
    setState(() {
      _filterSenders.remove(sender);
    });
    _addDebugLog('移除发送者过滤: $sender');
  }

  /// 导出数据
  Future<void> _exportData() async {
    try {
      final data = {
        'export_time': DateTime.now().toIso8601String(),
        'total_received': _totalReceived,
        'current_messages': _receivedMessages.map((m) => m.toMap()).toList(),
        'sender_stats': _senderStats,
        'settings': {
          'enable_background': _enableBackground,
          'filter_senders': _filterSenders,
          'auto_start_listening': _autoStartListening,
        },
        'debug_logs': _debugLogs,
      };

      final jsonString = JsonEncoder.withIndent('  ').convert(data);

      // 这里应该保存到文件，但示例中仅复制到剪贴板
      await Clipboard.setData(ClipboardData(text: jsonString));

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('数据已导出到剪贴板'),
          action: SnackBarAction(
            label: '查看',
            onPressed: () => _showExportData(jsonString),
          ),
        ),
      );
      _addDebugLog('数据导出成功');
    } catch (e) {
      _updateError('导出数据失败: $e');
    }
  }

  /// 显示导出数据
  void _showExportData(String data) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('导出的数据'),
        content: Container(
          width: double.maxFinite,
          height: 400,
          child: SingleChildScrollView(
            child: Text(data, style: TextStyle(fontFamily: 'monospace')),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 显示权限详情
  Future<void> _showPermissionDetails() async {
    try {
      final receiveStatus = await SmsPermissions.getPermissionStatus(
          'android.permission.RECEIVE_SMS');
      final readStatus = await SmsPermissions.getPermissionStatus(
          'android.permission.READ_SMS');

      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Row(
              children: [
                Icon(Icons.info_outline),
                SizedBox(width: 8),
                Text('权限详情'),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildPermissionRow('RECEIVE_SMS', receiveStatus),
                SizedBox(height: 8),
                _buildPermissionRow('READ_SMS', readStatus),
                SizedBox(height: 16),
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('提示：',
                          style: TextStyle(fontWeight: FontWeight.bold)),
                      Text('• 如果权限被永久拒绝，需要在设置中手动开启'),
                      Text('• 某些设备需要关闭电池优化'),
                      Text('• 确保允许应用后台活动'),
                    ],
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('关闭'),
              ),
              if (!_hasPermissions)
                ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context);
                    SmsPermissions.openAppSettings();
                  },
                  child: Text('去设置'),
                ),
            ],
          );
        },
      );
    } catch (e) {
      _updateError('获取权限详情失败: $e');
    }
  }

  Widget _buildPermissionRow(String permission, PermissionStatus status) {
    Color color;
    IconData icon;
    String text;

    switch (status) {
      case PermissionStatus.granted:
        color = Colors.green;
        icon = Icons.check_circle;
        text = '已授予';
        break;
      case PermissionStatus.denied:
        color = Colors.orange;
        icon = Icons.cancel;
        text = '被拒绝';
        break;
      case PermissionStatus.permanentlyDenied:
        color = Colors.red;
        icon = Icons.block;
        text = '永久拒绝';
        break;
      default:
        color = Colors.grey;
        icon = Icons.help;
        text = '未知';
    }

    return Row(
      children: [
        Icon(icon, color: color, size: 20),
        SizedBox(width: 8),
        Text(permission, style: TextStyle(fontWeight: FontWeight.bold)),
        Spacer(),
        Text(text, style: TextStyle(color: color)),
      ],
    );
  }

  /// 显示统计信息
  void _showStatistics() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.analytics),
            SizedBox(width: 8),
            Text('统计信息'),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildStatRow('总接收短信', _totalReceived.toString()),
              _buildStatRow('当前会话', _messageCount.toString()),
              _buildStatRow('最后短信时间', _lastSmsTime?.toString() ?? '无'),
              _buildStatRow('应用状态', _appLifecycleState),
              _buildStatRow('前台服务', _foregroundServiceRunning ? '运行中' : '已停止'),
              if (_senderStats.isNotEmpty) ...[
                SizedBox(height: 16),
                Text('发送者统计：', style: TextStyle(fontWeight: FontWeight.bold)),
                SizedBox(height: 8),
                ..._senderStats.entries.map((entry) =>
                    _buildStatRow(entry.key, entry.value.toString())),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: _resetStats,
            child: Text('重置'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildStatRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          Text(label + ':', style: TextStyle(fontWeight: FontWeight.w500)),
          Spacer(),
          Text(value),
        ],
      ),
    );
  }

  /// 显示调试信息
  void _showDebugLogs() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.bug_report),
            SizedBox(width: 8),
            Text('调试日志'),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          height: 400,
          child: ListView.builder(
            itemCount: _debugLogs.length,
            itemBuilder: (context, index) {
              return Padding(
                padding: EdgeInsets.symmetric(vertical: 2),
                child: Text(
                  _debugLogs[index],
                  style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                ),
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                _debugLogs.clear();
              });
              Navigator.pop(context);
            },
            child: Text('清空'),
          ),
          TextButton(
            onPressed: () {
              Clipboard.setData(ClipboardData(text: _debugLogs.join('\n')));
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('日志已复制到剪贴板')),
              );
            },
            child: Text('复制'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 显示设置页面
  void _showSettings() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.settings),
            SizedBox(width: 8),
            Text('设置'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SwitchListTile(
              title: Text('自动启动监听'),
              subtitle: Text('应用启动时自动开始监听'),
              value: _autoStartListening,
              onChanged: (value) {
                setState(() {
                  _autoStartListening = value;
                });
              },
            ),
            SwitchListTile(
              title: Text('后台监听'),
              subtitle: Text('启用前台服务进行后台监听'),
              value: _enableBackground,
              onChanged: (value) {
                setState(() {
                  _enableBackground = value;
                });
              },
            ),
            SwitchListTile(
              title: Text('显示调试信息'),
              subtitle: Text('在状态栏显示调试按钮'),
              value: _showDebugInfo,
              onChanged: (value) {
                setState(() {
                  _showDebugInfo = value;
                });
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SMS监听器完整测试'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          if (_showDebugInfo)
            IconButton(
              icon: Icon(Icons.bug_report),
              onPressed: _showDebugLogs,
              tooltip: '调试日志',
            ),
          IconButton(
            icon: Icon(Icons.analytics),
            onPressed: _showStatistics,
            tooltip: '统计信息',
          ),
          IconButton(
            icon: Icon(Icons.info_outline),
            onPressed: _showPermissionDetails,
            tooltip: '权限详情',
          ),
          PopupMenuButton<String>(
            onSelected: (value) {
              switch (value) {
                case 'settings':
                  _showSettings();
                  break;
                case 'export':
                  _exportData();
                  break;
                case 'debug':
                  _showDebugLogs();
                  break;
              }
            },
            itemBuilder: (context) => [
              PopupMenuItem(value: 'settings', child: Text('设置')),
              PopupMenuItem(value: 'export', child: Text('导出数据')),
              PopupMenuItem(value: 'debug', child: Text('调试日志')),
            ],
          ),
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 增强的状态卡片
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          _isListening
                              ? Icons.radio_button_checked
                              : Icons.radio_button_unchecked,
                          color: _isListening ? Colors.green : Colors.grey,
                        ),
                        SizedBox(width: 8),
                        Text(
                          '监听状态',
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                        Spacer(),
                        if (_foregroundServiceRunning)
                          Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 8, vertical: 2),
                            decoration: BoxDecoration(
                              color: Colors.blue,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text(
                              '前台服务',
                              style:
                                  TextStyle(color: Colors.white, fontSize: 10),
                            ),
                          ),
                      ],
                    ),
                    SizedBox(height: 8),
                    Text(_statusMessage),
                    if (_errorMessage.isNotEmpty) ...[
                      SizedBox(height: 8),
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.red[50],
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(color: Colors.red[200]!),
                        ),
                        child: Row(
                          children: [
                            Icon(Icons.error, color: Colors.red, size: 16),
                            SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                _errorMessage,
                                style: TextStyle(color: Colors.red[700]),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                    SizedBox(height: 8),
                    Wrap(
                      spacing: 16,
                      runSpacing: 4,
                      children: [
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              _hasPermissions
                                  ? Icons.check_circle
                                  : Icons.error,
                              color:
                                  _hasPermissions ? Colors.green : Colors.red,
                              size: 16,
                            ),
                            SizedBox(width: 4),
                            Text(
                              _hasPermissions ? '已有权限' : '缺少权限',
                              style: TextStyle(
                                color:
                                    _hasPermissions ? Colors.green : Colors.red,
                              ),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.settings,
                              size: 16,
                              color: Colors.grey[600],
                            ),
                            SizedBox(width: 4),
                            Text(
                              '后台监听: ${_enableBackground ? "开启" : "关闭"}',
                              style: TextStyle(color: Colors.grey[600]),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.apps,
                              size: 16,
                              color: Colors.grey[600],
                            ),
                            SizedBox(width: 4),
                            Text(
                              '应用: $_appLifecycleState',
                              style: TextStyle(color: Colors.grey[600]),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 控制按钮
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _hasPermissions && !_isListening
                        ? _startListening
                        : null,
                    icon: Icon(Icons.play_arrow),
                    label: Text('开始监听'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _isListening ? _stopListening : null,
                    icon: Icon(Icons.stop),
                    label: Text('停止监听'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),

            SizedBox(height: 8),

            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: !_hasPermissions ? _requestPermissions : null,
                    icon: Icon(Icons.security),
                    label: Text('申请权限'),
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: _loadSmsHistory,
                    icon: Icon(Icons.history),
                    label: Text('历史短信'),
                  ),
                ),
              ],
            ),

            SizedBox(height: 8),

            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: _getLastSms,
                    icon: Icon(Icons.message),
                    label: Text('最新短信'),
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () {
                      setState(() {
                        _enableBackground = !_enableBackground;
                      });
                    },
                    icon: Icon(
                        _enableBackground ? Icons.sync : Icons.sync_disabled),
                    label: Text('后台监听'),
                  ),
                ),
              ],
            ),

            SizedBox(height: 16),

            // 发送者过滤设置
            Card(
              child: Padding(
                padding: EdgeInsets.all(12.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.filter_list, size: 16),
                        SizedBox(width: 4),
                        Text('发送者过滤 (可选)',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                      ],
                    ),
                    SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _filterController,
                            decoration: InputDecoration(
                              hintText: '输入要过滤的发送者号码',
                              border: OutlineInputBorder(),
                              contentPadding: EdgeInsets.symmetric(
                                  horizontal: 12, vertical: 8),
                              prefixIcon: Icon(Icons.phone, size: 20),
                            ),
                            onSubmitted: (_) => _addSenderFilter(),
                          ),
                        ),
                        SizedBox(width: 8),
                        ElevatedButton(
                          onPressed: _addSenderFilter,
                          child: Text('添加'),
                        ),
                      ],
                    ),
                    if (_filterSenders.isNotEmpty) ...[
                      SizedBox(height: 8),
                      Wrap(
                        spacing: 8,
                        children: _filterSenders.map((sender) {
                          return Chip(
                            label: Text(sender),
                            deleteIcon: Icon(Icons.close, size: 16),
                            onDeleted: () => _removeSenderFilter(sender),
                            backgroundColor: Colors.blue[50],
                          );
                        }).toList(),
                      ),
                    ],
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 消息列表标题
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '实时短信 (${_receivedMessages.length})',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                Row(
                  children: [
                    if (_receivedMessages.isNotEmpty)
                      IconButton(
                        onPressed: _clearMessages,
                        icon: Icon(Icons.clear),
                        tooltip: '清空列表',
                      ),
                    IconButton(
                      onPressed: _exportData,
                      icon: Icon(Icons.file_download),
                      tooltip: '导出数据',
                    ),
                  ],
                ),
              ],
            ),

            SizedBox(height: 8),

            // 消息列表
            Expanded(
              child: _receivedMessages.isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.message, size: 64, color: Colors.grey),
                          SizedBox(height: 16),
                          Text(
                            '暂无新短信',
                            style: TextStyle(color: Colors.grey, fontSize: 18),
                          ),
                          SizedBox(height: 8),
                          Text(
                            '开始监听后，新收到的短信会显示在这里',
                            style: TextStyle(color: Colors.grey, fontSize: 12),
                            textAlign: TextAlign.center,
                          ),
                          if (!_isListening && _hasPermissions) ...[
                            SizedBox(height: 16),
                            ElevatedButton.icon(
                              onPressed: _startListening,
                              icon: Icon(Icons.play_arrow),
                              label: Text('开始监听'),
                            ),
                          ],
                        ],
                      ),
                    )
                  : ListView.builder(
                      itemCount: _receivedMessages.length,
                      itemBuilder: (context, index) {
                        final message = _receivedMessages[index];
                        return Card(
                          margin: EdgeInsets.only(bottom: 8),
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundColor: Colors.blue,
                              child: Text(
                                '${index + 1}',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 12),
                              ),
                            ),
                            title: Row(
                              children: [
                                Expanded(
                                  child: Text(
                                    message.address,
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                ),
                                Container(
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 6, vertical: 2),
                                  decoration: BoxDecoration(
                                    color: Colors.green[100],
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Text(
                                    'NEW',
                                    style: TextStyle(
                                      fontSize: 10,
                                      color: Colors.green[700],
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  message.body,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(height: 4),
                                Row(
                                  children: [
                                    Icon(Icons.access_time,
                                        size: 12, color: Colors.grey[600]),
                                    SizedBox(width: 4),
                                    Text(
                                      message.formattedDate,
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.grey[600],
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            trailing: Icon(Icons.arrow_forward_ios, size: 16),
                            onTap: () => _showSmsDetails(message),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
